package com.hanxin.shiro.realm;

import java.util.HashSet;
import java.util.Set;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

/**
 * @Author: hanxin
 * @Date: 2020/9/13 23:44
 * @Version 1.0
 */
public class CustomRealm extends AuthorizingRealm {

  // 授权
  protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

    String userName = (String) principalCollection.getPrimaryPrincipal();
    Set<String> roles = getRolesByUserName(userName);
    Set<String> permissions = getPermissionsByRole(roles);

    SimpleAuthorizationInfo simpleAuthorizationInfo = new
        SimpleAuthorizationInfo();
    // 设置角色
    simpleAuthorizationInfo.setRoles(roles);
    // 设置权限
    simpleAuthorizationInfo.setStringPermissions(permissions);
    return simpleAuthorizationInfo;
  }

  // 认证
  protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
      throws AuthenticationException {

    // 1.从主体传过来的认证信息中获取用户信息
    String userName = (String) authenticationToken.getPrincipal();
    // 2.通过用户名到数据库中获取凭证
    String password = getPasswordByUserName(userName);

    SimpleAuthenticationInfo authenticationInfo = new
        SimpleAuthenticationInfo("hx", password, "customrealm");

    // 加盐
    authenticationInfo.setCredentialsSalt(ByteSource.Util.bytes("hx"));
    return authenticationInfo;
  }

  /**
   * 模拟数据库 读取密码
   *
   * @param userName yonghu
   * @return mima
   */
  private String getPasswordByUserName (String userName) {
    // 读数据库 返回加密之后的密码
    return "bfd34b70eaa8c3c4912592265c8de910";
  }

  /**
   * 模拟数据库 读取权限
   *
   * @return set
   */
  private Set<String> getPermissionsByRole(Set<String> roles) {
    Set<String> set = new HashSet<String>();
    set.add("user:delete");
    return set;
  }

  /**
   * 模拟数据库 读取角色
   *
   * @return set
   */
  private Set<String> getRolesByUserName(String userName) {
    Set<String> set = new HashSet<String>();
    set.add("admin");
    return set;
  }

  public static void main(String[] args) {
    Md5Hash md5Hash = new Md5Hash("123456","hx");
    System.out.println(md5Hash);
  }

}
